﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data.SqlClient;
using System.Data;
//using CalendarApplication;

namespace DataService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class DalService : IDalService
    {
        Utilities util = new Utilities();

        public DalService()
        {

        }

        /***
         * Gets the salt for username provided, hashes pasword input with the retrieved salt
         * and calls the spGetLogin stored procedure
         * ***/
        public DataTable GetLogin(string Username, string Password)
        {
            byte[] salt = GetSalt(Username);
            byte[] hash = GenerateHash(Password, salt);

            SqlParameter[] parameters = new SqlParameter[]
            {
                new SqlParameter("@Username", Username),
                new SqlParameter("@Password", hash)
            };
            DataTable dt = util.ReadData("spGetLogin", parameters);
            return dt;
        }

        /***
         * Calls spRegister stored procedure which storres username, randomly generated salt
         * and hashed password in the database (tblUser)
         * ***/
        public void Register(string Username, byte[] Salt, byte[] Hash)
        {
            SqlParameter[] parameters = new SqlParameter[]
            {
                new SqlParameter("@Username", Username),
                new SqlParameter("@Salt", Salt),
                new SqlParameter("@Hash", Hash)
            };
            util.ExecuteProcedure("spRegister", parameters);
        }

        /***
         * Gets the salt value as a byte array associated with the username provided
         * ***/
        private byte[] GetSalt(string Username)
        {
            byte[] salt = new byte[0];
            SqlParameter[] parameters = new SqlParameter[]
            {
                new SqlParameter("@Username", Username)
            };
            DataTable dt = util.ReadData("spGetSalt", parameters);
            foreach (DataRow r in dt.Rows)
            {
                salt = (byte[])r["Salt"];
            }
            return salt;
        }
        
        /***
         * Algorith that hashes a password with the provided salt byte array
         * ***/
        private static byte[] GenerateHash(string password, byte[] salt)
        {
            //return GenerateHash(Encoding.UTF8.GetBytes(password), salt);
            byte[] pwd = Encoding.UTF8.GetBytes(password);
            var saltedPassword = new byte[password.Length + salt.Length];
            pwd.CopyTo(saltedPassword, 0);
            salt.CopyTo(saltedPassword, password.Length);

            return new SHA256Managed().ComputeHash(saltedPassword);
        }

        //TODO fix this
        //gridview doesn't exist here to parse
        //need to model entities in DAL

        //public void EnterAppointment(AppEnter calendarMain)
        //{
        //    SqlConnection conn = new SqlConnection(Utilities.DBConnection);
        //    conn.Open();

        //    //TODO abstract commands into stored procs
        //    SqlCommand sc = new SqlCommand("INSERT INTO tblCalendarMain ([Date], [StartTime], [EndTime], [Description])" +
        //    "VALUES (@Date, @StartTime, @Endtime, @Description)", conn);
        //    sc.Parameters.AddWithValue("@Date", calendarMain.Date);
        //    sc.Parameters.AddWithValue("@StartTime", calendarMain.StartTime);
        //    sc.Parameters.AddWithValue("@EndTime", calendarMain.EndTime);
        //    sc.Parameters.AddWithValue("@Description", calendarMain.Description);
        //    sc.ExecuteNonQuery();
        //    conn.Close();
        //}

        //public DataTable GridRefill()
        //{
        //    //TODO abstract
        //    SqlConnection conn = new SqlConnection(Utilities.DBConnection);
        //    conn.Open();

        //    //TODO abstract
        //    SqlCommand sc = new SqlCommand("SELECT * FROM tblCalendarMain WHERE Date='" + d + "'", conn);
        //    sc.CommandType = CommandType.Text;
        //    SqlDataAdapter da = new SqlDataAdapter(sc);
        //    DataTable ds = new DataTable();
        //    da.SelectCommand = sc;
        //    da.Fill(ds);
        //    //dataGridView1.DataSource = ds;
        //    //dataGridView1.Columns["pkID"].Visible = false;
        //    //dataGridView1.Columns["Date"].Visible = false;
        //    //dataGridView1.Columns["EndTime"].Visible = false;
        //    //dtpDate.Value = d;
        //    conn.Close();
        //    conn.Dispose();
        //    return ds;
        //}
    }
}
